//
//  Untitled.swift
//  PLDownload
//
//  Created by bin hu on 2025/7/7.
//
import Foundation

/* 标准文件下载 */
//class HTTPHandler: ProtocolHandler {
//    private var session: URLSession!
//    private var activeDownloadTask: URLSessionDownloadTask?
//    private var tempPath: String = ""
//    private let fileManager = FileManager.default
//    
//    init() {
//        let configuration = URLSessionConfiguration.default
//        session = URLSession(configuration: configuration, delegate: nil, delegateQueue: .main)
//    }
//    
//    func startDownload(task: DownloadTask) {
//        // 创建临时文件路径
//        tempPath = NSTemporaryDirectory() + UUID().uuidString + ".tmp"
//        
//        // 创建下载请求
//        let request = URLRequest(url: task.url)
//        
//        // 开始下载任务
//        activeDownloadTask = session.downloadTask(with: request)
//        activeDownloadTask?.resume()
//        
//        // 监听下载进度
//        session.downloadTask(with: request) { [weak self] location, response, error in
//            guard let self = self else { return }
//            
//            if let error = error {
//                task.completion(.failure(error))
//                return
//            }
//            
//            guard let location = location else {
//                task.completion(.failure(NSError(domain: "", code: -1, userInfo: nil)))
//                return
//            }
//            
//            // 移动文件到目标位置
//            do {
//                try self.fileManager.moveItem(at: location, to: URL(fileURLWithPath: task.destinationPath))
//                task.completion(.success(task.destinationPath))
//            } catch {
//                task.completion(.failure(error))
//            }
//        }.resume()
//    }
//    
//    func pauseDownload() {
//        activeDownloadTask?.cancel(byProducingResumeData: { [weak self] resumeData in
//            guard let self = self, let data = resumeData else { return }
//            // 保存恢复数据到临时文件
//            try? data.write(to: URL(fileURLWithPath: self.tempPath))
//        })
//        activeDownloadTask = nil
//    }
//    
//    func resumeDownload() {
//        // 检查临时文件是否存在
//        guard fileManager.fileExists(atPath: tempPath),
//              let resumeData = try? Data(contentsOf: URL(fileURLWithPath: tempPath)) else {
//            startDownload(task: task)
//            return
//        }
//        
//        // 获取已下载文件大小
//        let fileSize = getFileSize(atPath: tempPath)
//        
//        // 设置Range头
//        var request = URLRequest(url: task.url)
//        request.addValue("bytes=\(fileSize)-", forHTTPHeaderField: "Range")
//        
//        // 恢复下载
//        activeDownloadTask = session.downloadTask(withResumeData: resumeData)
//        activeDownloadTask?.resume()
//    }
//    
//    private func getFileSize(atPath path: String) -> Int64 {
//        do {
//            let attributes = try fileManager.attributesOfItem(atPath: path)
//            return attributes[.size] as? Int64 ?? 0
//        } catch {
//            return 0
//        }
//    }
//    
//}

// HTTP/HTTPS处理器
class HTTPHandler: ProtocolHandler {
    var task: DownloadTask
    private var downloadTask: URLSessionDownloadTask?
    private var resumeData: Data?
    private var session: URLSession!
    
    init(task: DownloadTask) {
        self.task = task
        self.session = URLSession(
            configuration: .default,
            delegate: nil,
            delegateQueue: nil
        )
    }
    
    func startDownload(manager: DownloadManager) {
        downloadTask = session.downloadTask(with: task.url) { [weak self] location, response, error in
            guard let self = self else { return }
            
            if let error = error {
                manager.updateTaskState(id: self.task.id, state: .failed(error: error.localizedDescription))
                return
            }
            
            guard let location = location else {
                manager.updateTaskState(id: self.task.id, state: .failed(error: "Invalid file location"))
                return
            }
            
            do {
                let destination = manager.fileManager.localPath(for: self.task)
                try FileManager.default.moveItem(at: location, to: destination)
                manager.updateTask(id: self.task.id, state: .completed, localPath: destination)
            } catch {
                manager.updateTaskState(id: self.task.id, state: .failed(error: error.localizedDescription))
            }
        }
        
        downloadTask?.resume()
        manager.updateTaskState(id: task.id, state: .downloading(progress: 0))
    }
    
    func pauseDownload() {
        downloadTask?.cancel(byProducingResumeData: { [weak self] data in
            self?.resumeData = data
        })
    }
    
    func resumeDownload() {
        if let resumeData = resumeData {
            downloadTask = session.downloadTask(withResumeData: resumeData)
            downloadTask?.resume()
        } else {
            downloadTask?.resume()
        }
    }
    
    func cancelDownload() {
        downloadTask?.cancel()
        resumeData = nil
    }
}

